package com.mida.dms.knw.service.impl;

import com.mida.dms.knw.mapper.KnwCodingConceptualDomainMapper;
import com.mida.dms.knw.mapper.KnwConceptualDomainMapper;
import com.mida.dms.knw.Result.BaseResult;
import com.mida.dms.knw.entity.KnwCodingConceptualDomain;
import com.mida.dms.knw.entity.KnwConceptualDomain;
import com.mida.dms.knw.entity.vo.KccdPage;
import com.mida.dms.knw.entity.vo.KnwCodingConceptualDomainPageVo;
import com.mida.dms.knw.entity.vo.KnwConceptualDomainVo;
import com.mida.dms.knw.service.KnwConceptualDomainService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class KnwConceptualDomainServiceImpl extends BaseResult implements KnwConceptualDomainService {

    @Autowired
    private KnwConceptualDomainMapper knwConceptualDomainMapper;

    @Autowired
    private KnwCodingConceptualDomainMapper knwCodingConceptualDomainMapper;


    /**
     * ID生成器
     */
    @Autowired
    private SoidService soidService;
//    @Autowired
//    private OIDGanerator oIDGanerator;
    /**
     * 根据概念soid，查询概念域相关数据业务处理
     *
     * @param conceptualSoid
     * @return
     */
    @Override
    public ListResult<List<KnwConceptualDomainVo>> getKnwConceptualDomain(long conceptualSoid) {

        log.info("开始获取一个概念soid" + conceptualSoid);
        StopWatch st = StopWatch.createStarted();
        ListResult< List<KnwConceptualDomainVo>> list = new ListResult< List<KnwConceptualDomainVo>>();
        List<KnwConceptualDomainVo> listVo = new ArrayList<KnwConceptualDomainVo>();
        try {
            listVo = knwConceptualDomainMapper.selectByConceptualsoid2(conceptualSoid);
            buildListSuccess(list,listVo);
        } catch (Exception e) {
            log.error("根据概念soid，查询概念域相关数据业务处理异常",e);
            buildListWarn(list, "根据概念soid，查询概念域相关数据业务处理异常");
        }finally {
            st.stop();
            log.info("本次查询耗时:"+st.getTime()+"ms");
        }
        return list;
    }

    /**
     * 根据概念soid，分页查询概念域列表业务处理
     *
     * @param domainSoid
     * @return
     */
    @Override
    public ListResult<PageResultVo<KnwCodingConceptualDomainPageVo>> findPage(Long domainSoid, Long currentPage, Long pageSize) {

        log.info("开始分页查询,查询条件:" + domainSoid);
        PageResultVo pvo = new PageResultVo();
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwCodingConceptualDomain> list = null;
        try {
            Page page = new Page(currentPage, pageSize);
            pvo.setPage(page);

            KccdPage kccdPage = new KccdPage();
            kccdPage.setDomainSoid(domainSoid);
            page = new Page(currentPage, pageSize);
            int num = knwCodingConceptualDomainMapper.findPageCount(kccdPage);

            if (num == 0) {
                pvo.setPage(null);
                pvo.setList(null);
            } else {
                page.setTotalCount(num);
                kccdPage.setPageSt(page.getBeginIndex());
                kccdPage.setPageEd(currentPage * page.getEveryPage());
                list = knwCodingConceptualDomainMapper.findPage(kccdPage);

                pvo.setPage(page);
                pvo.setList(list);
            }

            buildListSuccess(result,pvo);
        } catch (Exception e) {
            list = new ArrayList<KnwCodingConceptualDomain>();
            pvo.setList(list);
            log.error("分页查询概念域列表业务处理异常", e);
            buildListWarn(result, "分页查询概念域列表业务处理异常");
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");
        }
        return result;
    }

    /**
     * 绑定编码体系业务处理
     *
     * @param domainSoid
     * @param derailCodingSystemSoids
     * @return
     */
    @Override
    public ActionResult add(long domainSoid, String derailCodingSystemSoids) {
        ActionResult result = new ActionResult();

        try {

            if (domainSoid == 0 || StringUtils.isEmpty(derailCodingSystemSoids)) {
                result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                result.setMessage("概念域ID或编码体系ID不能为空");
                return result;
            }

            String[] str = derailCodingSystemSoids.split(",");

            KnwCodingConceptualDomain kccd;
            Integer countIsPre = knwCodingConceptualDomainMapper.countIsPreByDomainSoid(domainSoid);
            for (int i = 0; i < str.length; i++) {
                //校验是否重复绑定
               int count= knwCodingConceptualDomainMapper.countByDomainSoidAndDerailCodingSystemSoid(domainSoid,Long.valueOf(str[i]));
                if (count!=0) {//若有，则不再绑定，跳过进行下一个
                    continue;
                }
                kccd = new KnwCodingConceptualDomain();
                kccd.setDomainSoid(domainSoid);
                kccd.setDerailCodingSystemSoid(Long.valueOf(str[i]));
//                kccd.setCodingDomainSoid(oIDGanerator.getSOID());
                kccd.setCodingDomainSoid(soidService.getSoid());

                if (countIsPre!=0) {//如果有首选，后绑定的isPreferred设置0
                    kccd.setIsPreferred(0l);
                }else{
                    if (i == 0) {//如果无首选，第一个isPreferred设置1
                        kccd.setIsPreferred(1l);
                    } else {
                        kccd.setIsPreferred(0l);
                    }
                }

                knwCodingConceptualDomainMapper.insertSelective(kccd);
            }

            buildActionSuccess(result);
        } catch (Exception ex) {
            log.error("绑定编码体系失败", ex);
            buildActionWarn(result, ex);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }

    /**
     * 解绑业务处理
     *
     * @param codingDomainSoid
     * @return
     */
    @Override
    public ActionResult delete(long codingDomainSoid) {
        ActionResult result = new ActionResult();
        try {
            knwCodingConceptualDomainMapper.deleteByPrimaryKey(codingDomainSoid);
            buildActionSuccess(result);
        } catch (Exception ex) {
            log.error("绑定编码体系失败", ex);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(result, ex);
        }
        return result;
    }

    /**
     * 更新首选标识业务处理
     * @param codingDomainSoid
     * @param domainSoid
     * @return
     */
    @Override
    public ActionResult update(long codingDomainSoid, long domainSoid) {
        ActionResult result = new ActionResult();
        Long domainSoidTmp = null;
         try {
             // 根据概念域，查询概念域与编码体系关系列表
             List<KnwCodingConceptualDomain> list
                     = knwCodingConceptualDomainMapper.selectByDomainSoid(domainSoid);

             for (KnwCodingConceptualDomain k: list) {
                 if (k.getIsPreferred() == 1l) {
                     domainSoidTmp = k.getCodingDomainSoid();
                     break;
                 }
             }

             // 更新已有的首选
             if (domainSoidTmp != null) {
                 knwCodingConceptualDomainMapper.updateIsPreferredOff(domainSoidTmp);
             }

             // 更新首选标识
             knwCodingConceptualDomainMapper.updateIsPreferredOn(codingDomainSoid);

             buildActionSuccess(result);
         } catch (Exception ex) {
             log.error("设置概念描述首选发送异常", ex);
             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
             buildActionWarn(result, "更新首选标识失败");
         }
        return result;
    }

    @Override
    public ListResult<List<KnwCodingConceptualDomainPageVo>> getCodingDomainAll(Long domainSoid) {

        log.info("开始概念域查询所有编码体系,查询条件:");
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwCodingConceptualDomainPageVo> list = null;
        try {
            list = knwCodingConceptualDomainMapper.getCodingDomainAll(domainSoid);
            buildListSuccess(result,list);
        } catch (Exception e) {
            list = new ArrayList<KnwCodingConceptualDomainPageVo>(0);
            log.error("概念域查询所有编码体系发送异常",e);
            buildListWarn(result, "概念域查询所有编码体系发送异常");
        }finally {
            st.stop();
            log.info("本次概念域查询所有编码体系耗时:"+st.getTime()+"ms");

        }
        return result;
    }

    @Override
    public ListResult<List<KnwConceptualDomain>> getAllCodingDomain() {

        log.info("开始查询所有概念域,查询条件:");
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwConceptualDomain> list = null;
        try {
            list = knwConceptualDomainMapper.findAll();
            buildListSuccess(result,list);
        } catch (Exception e) {
            list = new ArrayList<KnwConceptualDomain>(0);
            log.error("查询所有概念域发送异常",e);
            buildListWarn(result, "查询所有概念域发送异常");
        }finally {
            st.stop();
            log.info("本次查询所有概念域耗时:"+st.getTime()+"ms");

        }
        return result;
    }
}
